package com.wwu.system.quartz;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.wwu.common.utils.DateUtils;
import com.wwu.system.entity.OperLog;
import com.wwu.system.entity.SysQuartzLog;
import com.wwu.system.service.IOperLogService;
import com.wwu.system.service.ISysQuartzLogService;
import com.wwu.system.service.ISysQuartzService;
import com.wwu.system.vo.QueryVO;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * 定时清理操作日志任务
 * @author 一蓑烟雨
 * @version 1.0.0
 * @date 2023-08-16 15:12
 */
@Slf4j
public class DealOperLogJob implements Job {
    @Resource
    private IOperLogService operLogService;
    @Resource
    private ISysQuartzLogService sysQuartzLogService;
    @Resource
    private ISysQuartzService sysQuartzService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        //获取触发器cronTrigger传递的参数
        JobDataMap dataMap = context.getTrigger().getJobDataMap();
        log.info("----------【{}】任务执行开始，执行频率为：{}----------", dataMap.get("quartzName"),dataMap.get("quartzCron"));

        //删除日志业务
        QueryVO queryVO = new QueryVO();
        JSONObject jsonObject = JSON.parseObject((String) dataMap.get("quartzParam"));
        String dayHourOfDiff = jsonObject.getString("dayHourOfDiff");
        int dayHour = 0;
        if(StringUtils.hasText(dayHourOfDiff) && dayHourOfDiff.indexOf("d")>0){
            dayHour = Integer.parseInt(dayHourOfDiff.substring(0, dayHourOfDiff.indexOf("d")));
            queryVO.setStartDate(DateUtils.getDateDiff(new Date(),-365*2));
            queryVO.setEndDate(DateUtils.getDateDiff(new Date(),dayHour));
        }else{
            queryVO.setStartDate(DateUtils.getDateDiff(new Date(),-365*2));
            queryVO.setEndDate(DateUtils.getDateDiff(new Date(),-7));
        }
        int count = operLogService.deleteOperLog(new OperLog(), queryVO);

        //记录任务日志
        SysQuartzLog sysQuartzLog = new SysQuartzLog();
        sysQuartzLog.setQuartzId((String) dataMap.get("quartzId"));
        sysQuartzLog.setQuartzClass((String) dataMap.get("quartzClass"));
        sysQuartzLog.setQuartzParam((String) dataMap.get("quartzParam"));
        sysQuartzLog.setExecTime(LocalDateTime.now());
        if(count >= 0){
            sysQuartzLog.setExecStatus(0);
            sysQuartzLog.setExecDesc("共处理"+count+"条数据");
        }else {
            sysQuartzLog.setExecStatus(1);
        }
        sysQuartzService.updateQuartzExecStatus(sysQuartzLog.getQuartzId(),sysQuartzLog.getExecStatus());
        sysQuartzLogService.saveQuartzLog(sysQuartzLog);

        log.info("-----------【{}】任务执行结束----------",dataMap.get("quartzName"));
    }
}
